package com.zhou.base.components.bs.common.util;

import com.google.common.base.CaseFormat;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xianfeng
 * @date 2023/7/20 14:45
 * @description:
 */
public class SortFeildUtil {

    /**
     * 升序
     */
    private static final String DESC_KEY = "desc";

    /**
     * 降序
     */
    private static final String ASC_KEY = "asc";

    /**
     * @param sortFieldMap 排序的字段 Key位字段，value为固定值 desc，或asc
     * @param allFields    允许排序的字段
     * @return java.lang.String
     * @description 获取排序的字符串，如果使用queryWrapper.last(order by field1 desc,feild2 desc);
     * @author xianfeng
     * @date 2023/7/20 15:06
     */
    public static String getSortStr(Map<String, String> sortFieldMap, List<String> allFields) {
        StringBuilder sortStr = new StringBuilder();
        if (sortFieldMap != null && sortFieldMap.size() > 0) {
            sortFieldMap.forEach((k, v) -> {
                if (k != null && v != null && allFields != null && allFields.contains(k)) {
                    if (ASC_KEY.equals(v) || DESC_KEY.equals(v)) {
                        sortStr.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, k) + " " + v + ",");
                    }
                }
            });
            if (sortStr.length() > 0) {
                return "order by " + sortStr.substring(0, sortStr.length() - 1);
            }
        }
        return sortStr.toString();
    }

    public static void main(String[] args) {
        Map<String, String> sortFieldMap = new LinkedHashMap<>();
        sortFieldMap.put("feild1Name", DESC_KEY);
        sortFieldMap.put("feild2Name", ASC_KEY);
        sortFieldMap.put("feild3Name", DESC_KEY);

        List<String> list = new ArrayList<>();
        list.add("feild2Name");
        list.add("feild3Name");
        String sortStr = getSortStr(sortFieldMap, list);
        System.out.println(sortStr);

        String usernamePassword = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "usernamePassword");
        System.out.println(usernamePassword);
    }
}
